package cn.arikeky.org.controller;


import cn.arikeky.basic.anno.PreAuthorize;
import cn.arikeky.basic.config.BussinessException;
import cn.arikeky.basic.util.AjaxResult;
import cn.arikeky.basic.util.PageList;
import cn.arikeky.org.domain.Department;
import cn.arikeky.org.query.DepartmentQuery;
import cn.arikeky.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(value = "部门的API",description="部门相关的CRUD功能")
public class DepartmentController {


    @Autowired
    private IDepartmentService departmentService;

    /**
     * 添加/修改
     */
    @PutMapping
    @PreAuthorize(name = "dept添加/修改部门数据", sn = "dept:addOrUpdate")
    public AjaxResult addOrUpdate(@RequestBody Department department){
        if (null == department.getId()){
            // 添加
            departmentService.add(department);
        }else {
            // 修改
            departmentService.update(department);
        }
        return AjaxResult.me().success();
    }

    /**
     * 删除 delete localhost:8080/dept/1
     */
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "dept删除部门数据", sn = "dept:delete")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
        } catch(BussinessException ex){
            ex.printStackTrace();
            return AjaxResult.me().fail("参数不能为空");
        }

        return AjaxResult.me().success();
    }

    /**
     * 查询所有
     */
    @GetMapping
    @ApiOperation(value = "查询所有部门数据" )
    @PreAuthorize(name = "dept查询所有部门数据", sn = "dept:findAll")
    public List<Department> findAll(){
        return departmentService.findAll();
    }

    /**
     * 根据id查询一个
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "通过deptID查询" )
    public Department findById(@ApiParam(value="ID属性",required = true) @PathVariable("id") Long id){
        return departmentService.findById(id);
    }

    /**
     *
     * 分页查询
     */
    @PostMapping
    public PageList<Department> queryByPage(@RequestBody DepartmentQuery query){
        return departmentService.queryByPage(query);
    }
    /**
     * 批量删除
     */
    @PatchMapping
    @PreAuthorize(name = "通过dept批量删除", sn = "dept:batchDel")
    public AjaxResult batchDel(@RequestBody List<Long> ids) {
        departmentService.batchDel(ids);
        return AjaxResult.me().success();
    }

    @PostMapping("/tree")
    @PreAuthorize(name = "部门树", sn = "dept:tree")
    public List<Department> batchTree() {
        return departmentService.batchTree();

    }
}
